package com.cheeven.amazonbooksreviewscores;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Map;
import java.util.TreeMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class GetSingleBookByURL {

    GetPage page = new GetPage();

    public static void main(String[] args) throws Exception {
        //String url = "http://www.amazon.com/Catching-Fire-Second-Hunger-Games/dp/0439023491/ref=ntt_at_ep_dpt_1";
        //String url = "http://www.amazon.co.uk/Polaroids-Helmut-Newton/dp/383652886X";
        String url = "http://www.amazon.co.uk/Peoples-Republic-Robert-Muchamore/dp/0340999195";
        String outputFile = "top100-single-details.html";

        if (args.length > 0) {
            url = args[0];
        }
        if (args.length > 1) {
            outputFile = args[1];
        }

        GetSingleBookByURL t = new GetSingleBookByURL();
        Map<String, String> book = t.findBook(url);

        System.out.println();
        for (String key : book.keySet()) {
            System.out.println(key + ":\t" + book.get(key));
        }
        System.out.println();

        File scoreList = new File(outputFile);
        PrintWriter out = new PrintWriter(new FileWriter(scoreList));

        out.println(Top100ReportTemplate.HEADER);
        Top100ReportTemplate.doBody(book, out);
        out.flush();
        out.println(Top100ReportTemplate.FOOTER);

        out.close();

    }

    public Map<String, String> findBook(String urlString) throws Exception {

        TreeMap<String, String> bookInfo = new TreeMap<String, String>();
        bookInfo.put("basic.url", urlString);

        URL url = new URL(urlString);

        Document domdoc = page.getPageDOM(url);

        if (domdoc == null) {
            return bookInfo;
        }

        bookInfo.put("basic.title", page.getPageInfo(domdoc, "//span[@id='btAsinTitle']"));
        bookInfo.put("basic.author", page.getPageInfo(domdoc, "//div[@class='buying']//span[@id='btAsinTitle']/../..//a/text()"));
        bookInfo.put("basic.ASIN", page.getPageInfo(domdoc, "//form[@name='handleBuy']/input[@name='ASIN']/@value"));
        bookInfo.put("basic.merchantID", page.getPageInfo(domdoc, "//form[@name='handleBuy']/input[@name='merchantID']/@value"));
        bookInfo.put("basic.storeID", page.getPageInfo(domdoc, "//form[@name='handleBuy']/input[@name='storeID']/@value"));
        bookInfo.put("price.listPrice", page.getPageInfo(domdoc, "//span[@class='listprice']"));
        bookInfo.put("price.shipping", page.getPageInfo(domdoc, "//b[@class='priceLarge']/../b[2]"));
        bookInfo.put("price.price", page.getPageInfo(domdoc, "//b[@class='priceLarge']"));
        bookInfo.put("price.youSave", page.getPageInfo(domdoc, "//tr[@class='youSavePriceRow']/td[@class='price']"));

        bookInfo.put("price.inStock", page.getPageInfo(domdoc, "//form[@id='handleBuy']/table[3]/tr[3]/td/div[@class='buying']/span"));
        bookInfo.put("price.shippedBy", page.getPageInfo(domdoc, "//form[@id='handleBuy']/table[3]/tr[3]/td/div[@class='buying']/b"));

        NodeList contentList = page.getPageInfoNodeList(domdoc, "//div[@class='content']/ul/li/b");
        for (int i = 0; i < contentList.getLength(); i++) {
            Element cc = (Element) contentList.item(i);
            String value = page.getPageInfo(cc, "../text()");
            String name = page.getPageInfo(cc, "text()");
            if (name.contains(":")) {
                name = name.substring(0, name.indexOf(":")).trim();
            }
            value = value.trim();

            bookInfo.put("content." + name.replace(" ", "."), value);
        }

        if (bookInfo.containsKey("content.Publisher")) {
            String publisher = bookInfo.get("content.Publisher");
            bookInfo.put("content.PublishDate", removeBrackets(publisher.substring(publisher.indexOf("("))));
            bookInfo.put("content.PublisherName", publisher.substring(0, publisher.indexOf("(")));
        }


        String salesRank = page.getPageInfo(domdoc, "//li[@id='SalesRank']");
        //System.out.println(salesRank);
        if (salesRank != null) {
            bookInfo.put("salesRank", salesRank);
            String[] t = salesRank.split("#");
            for (int k = 2; k < t.length; k++) {
                bookInfo.put("salesRank.sub" + (k - 1) + ".cat", t[k].substring(t[k].indexOf("in") + 2).trim());
                bookInfo.put("salesRank.sub" + (k - 1) + ".rank", t[k].substring(0, t[k].indexOf("in")).trim());
            }
            if (t.length >= 2) {
                bookInfo.put("salesRank.cat", t[1].substring(t[1].indexOf("in") + 2).trim());
                bookInfo.put("salesRank.rank", t[1].substring(0, t[1].indexOf("in")).trim());
            }
        }

        bookInfo.put("review.total", page.getPageInfo(domdoc, "//div[@id='customerReviews']/div/table/tr/td/table/tr/td/div/div/b"));
        bookInfo.put("review.5star", parseInt(page.getPageInfo(domdoc, "//div[@id='customerReviews']/div/table/tr/td/table/tr/td/div/table/tr[1]/td[3]")));
        bookInfo.put("review.4star", parseInt(page.getPageInfo(domdoc, "//div[@id='customerReviews']/div/table/tr/td/table/tr/td/div/table/tr[2]/td[3]")));
        bookInfo.put("review.3star", parseInt(page.getPageInfo(domdoc, "//div[@id='customerReviews']/div/table/tr/td/table/tr/td/div/table/tr[3]/td[3]")));
        bookInfo.put("review.2star", parseInt(page.getPageInfo(domdoc, "//div[@id='customerReviews']/div/table/tr/td/table/tr/td/div/table/tr[4]/td[3]")));
        bookInfo.put("review.1star", parseInt(page.getPageInfo(domdoc, "//div[@id='customerReviews']/div/table/tr/td/table/tr/td/div/table/tr[5]/td[3]")));
        bookInfo.put("review.average", page.getPageInfo(domdoc, "//div[@id='customerReviews']/div/table/tr/td/table/tr/td[3]/div[3]/span/@title"));

        String cc = page.getPageInfo(domdoc, "//div[@id='CustomerDiscussions']//div[@class='bucketFooter']/b/a");
        if (cc != null && cc.split(" ").length > 2) {
            bookInfo.put("customerDiscussion.count", cc.split(" ")[2]);
        }
        bookInfo.put("customerDiscussion.url", page.getPageInfo(domdoc, "//div[@id='CustomerDiscussions']//div[@class='bucketFooter']/b/a/@href"));

        Element twisterMediaMatrix = page.getPageInfoElement(domdoc, "//table[@class='twisterMediaMatrix']//div[@class='cBoxInner']/table");
        if (twisterMediaMatrix != null) {
            bookInfo.put("twisterMediaMatrix.kindle.url", page.getPageInfo(twisterMediaMatrix, "tbody[@id='kindle_meta_binding_winner']/tr/td[2]/a/@href"));
            bookInfo.put("twisterMediaMatrix.kindle.format", page.getPageInfo(twisterMediaMatrix, "tbody[@id='kindle_meta_binding_winner']/tr/td[2]/a/text()"));
            bookInfo.put("twisterMediaMatrix.kindle.amazonPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='kindle_meta_binding_winner']/tr/td[3]"));
            bookInfo.put("twisterMediaMatrix.kindle.newFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='kindle_meta_binding_winner']/tr/td[5]"));
            bookInfo.put("twisterMediaMatrix.kindle.usedFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='kindle_meta_binding_winner']/tr/td[6]"));

            bookInfo.put("twisterMediaMatrix.hardcover.url", page.getPageInfo(twisterMediaMatrix, "tbody[@id='hardcover_meta_binding_winner']/tr/td[2]/a/@href"));
            bookInfo.put("twisterMediaMatrix.hardcover.format", page.getPageInfo(twisterMediaMatrix, "tbody[@id='hardcover_meta_binding_winner']/tr/td[2]/a/text()"));
            bookInfo.put("twisterMediaMatrix.hardcover.amazonPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='hardcover_meta_binding_winner']/tr/td[3]"));
            bookInfo.put("twisterMediaMatrix.hardcover.newFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='hardcover_meta_binding_winner']/tr/td[5]"));
            bookInfo.put("twisterMediaMatrix.hardcover.usedFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='hardcover_meta_binding_winner']/tr/td[6]"));

            bookInfo.put("twisterMediaMatrix.paperback.url", page.getPageInfo(twisterMediaMatrix, "tbody[@id='paperback_meta_binding_winner']/tr/td[2]/a/@href"));
            bookInfo.put("twisterMediaMatrix.paperback.format", page.getPageInfo(twisterMediaMatrix, "tbody[@id='paperback_meta_binding_winner']/tr/td[2]/a/text()"));
            bookInfo.put("twisterMediaMatrix.paperback.amazonPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='paperback_meta_binding_winner']/tr/td[3]"));
            bookInfo.put("twisterMediaMatrix.paperback.newFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='paperback_meta_binding_winner']/tr/td[5]"));
            bookInfo.put("twisterMediaMatrix.paperback.usedFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='paperback_meta_binding_winner']/tr/td[6]"));

            bookInfo.put("twisterMediaMatrix.massmarketpaperback.url", page.getPageInfo(twisterMediaMatrix, "tbody[@id='mass_market_paperback_meta_binding_winner']/tr/td[2]/a/@href"));
            bookInfo.put("twisterMediaMatrix.massmarketpaperback.format", page.getPageInfo(twisterMediaMatrix, "tbody[@id='mass_market_paperback_meta_binding_winner']/tr/td[2]/a/text()"));
            bookInfo.put("twisterMediaMatrix.massmarketpaperback.amazonPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='mass_market_paperback_meta_binding_winner']/tr/td[3]"));
            bookInfo.put("twisterMediaMatrix.massmarketpaperback.newFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='mass_market_paperback_meta_binding_winner']/tr/td[5]"));
            bookInfo.put("twisterMediaMatrix.massmarketpaperback.usedFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='mass_market_paperback_meta_binding_winner']/tr/td[6]"));

            bookInfo.put("twisterMediaMatrix.audiobooks.url", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_meta_binding_winner']/tr/td[2]/a/@href"));
            bookInfo.put("twisterMediaMatrix.audiobooks.format", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_meta_binding_winner']/tr/td[2]/a/text()"));
            bookInfo.put("twisterMediaMatrix.audiobooks.amazonPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_meta_binding_winner']/tr/td[3]"));
            bookInfo.put("twisterMediaMatrix.audiobooks.newFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_meta_binding_winner']/tr/td[5]"));
            bookInfo.put("twisterMediaMatrix.audiobooks.usedFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_meta_binding_winner']/tr/td[6]"));

            bookInfo.put("twisterMediaMatrix.other.url", page.getPageInfo(twisterMediaMatrix, "tbody[@id='other_meta_binding_winner']/tr/td[2]/a/@href"));
            bookInfo.put("twisterMediaMatrix.other.format", page.getPageInfo(twisterMediaMatrix, "tbody[@id='other_meta_binding_winner']/tr/td[2]/a/text()"));
            bookInfo.put("twisterMediaMatrix.other.amazonPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='other_meta_binding_winner']/tr/td[3]"));
            bookInfo.put("twisterMediaMatrix.other.newFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='other_meta_binding_winner']/tr/td[5]"));
            bookInfo.put("twisterMediaMatrix.other.usedFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='other_meta_binding_winner']/tr/td[6]"));

            bookInfo.put("twisterMediaMatrix.audiobooksDigital.url", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_digital_meta_binding_winner']/tr/td[2]/a/@href"));
            bookInfo.put("twisterMediaMatrix.audiobooksDigital.format", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_digital_meta_binding_winner']/tr/td[2]/a/text()"));
            bookInfo.put("twisterMediaMatrix.audiobooksDigital.amazonPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_digital_meta_binding_winner']/tr/td[3]"));
            bookInfo.put("twisterMediaMatrix.audiobooksDigital.newFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_digital_meta_binding_winner']/tr/td[5]"));
            bookInfo.put("twisterMediaMatrix.audiobooksDigital.usedFromPrice", page.getPageInfo(twisterMediaMatrix, "tbody[@id='audiobooks_digital_meta_binding_winner']/tr/td[6]"));
        }



        return bookInfo;
    }

    private String removeBrackets(String x) {
        if (x == null) {
            return "";
        }
        if (!x.contains("(") && !x.contains(")")) {
            return x;
        }
        x = x.substring(x.indexOf("(") + 1, x.indexOf(")"));
        return x;
    }
    DecimalFormat format = new DecimalFormat("#,##0");

    private String parseInt(String x) throws ParseException {
        x = removeBrackets(x);
        if (!"".equals(x)) {
            x = String.valueOf(format.parse((removeBrackets(x))));
        }
        return x;
    }
}
